package tools

import (
	"fmt"
	"github.com/zeromicro/go-zero/core/jsonx"
	"github.com/zeromicro/go-zero/core/logx"
	"reflect"
	"strings"
)

func BeanToJson(any interface{}) string {
	toString, err := jsonx.MarshalToString(any)
	if err != nil {
		logx.Error("beanToJson err:", err.Error())
		return ""
	}
	return toString
}

func JsonToBean(jsonStr string, targetObj any) {
	err := jsonx.UnmarshalFromString(jsonStr, targetObj)
	if err != nil {
		logx.Error("JsonToBean err:", err.Error())
		return
	}
}

// BeanToMapForReflect bean转map 不支持嵌套
func BeanToMapForReflect(obj interface{}) (map[string]interface{}, error) {
	if obj == nil {
		logx.Error("input obj is nil")
		return nil, fmt.Errorf("input obj is nil")
	}
	elems := reflect.ValueOf(obj)
	types := reflect.TypeOf(obj)
	m := make(map[string]interface{})
	for i := 0; i < types.NumField(); i++ {
		name := types.Field(i).Name
		m[strings.ToLower(name)[:1]+name[1:]] = elems.Field(i).Interface()
	}
	return m, nil
}
